import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zego_express_engine/zego_express_engine.dart';
import 'dart:math' as math;
import 'dart:async';
import 'dart:typed_data';
import '../services/audio_stream_service.dart';
import '../services/ms_websocket_trans_service.dart';
import '../constants/language_list.dart';
import 'video_chat.dart';
import '../app_logger.dart';

class VideoConversationScreen extends StatefulWidget {
  final String? roomId;
  final String? userId;
  final bool showShareSheet;
  final String? fromLanguage;
  final String? toLanguage;

  const VideoConversationScreen({
    Key? key,
    this.roomId,
    this.userId,
    this.showShareSheet = false,
    this.fromLanguage,
    this.toLanguage,
  }) : super(key: key);

  @override
  State<VideoConversationScreen> createState() => _VideoConversationScreenState();
}

class _VideoConversationScreenState extends State<VideoConversationScreen> {
  // 视频相关
  Widget? _localVideoView;
  Widget? _remoteVideoView;
  int _localViewID = -1;
  int _remoteViewID = -1;

  // 状态管理
  bool _isJoined = false;
  bool _isMicEnabled = true;
  bool _isCameraEnabled = true;
  bool _isFrontCamera = true;
  bool _isPublishing = false;
  List<String> _remoteUsers = [];
  bool _isEngineInitialized = false;
  bool _isPlayingRemoteStream = false;

  // 房间信息
  String _roomId = '';
  String _userId = '';

  // 音频流服务
  final AudioStreamService _audioService = AudioStreamService();
  bool _audioServiceActive = false;
  int _localAudioFrameCount = 0;
  int _remoteAudioFrameCount = 0;

  // WebSocket翻译服务
  final MSWebSocketTransService _translationService = MSWebSocketTransService();
  bool _translationServiceConnected = false;

  // 语言选择 - 使用BCP-47标准代码
  String _fromLanguage = LanguageCodes.zhCN; // 中文
  String _toLanguage = LanguageCodes.enUS;   // 英语

  // 通话时间
  Timer? _callTimer;
  int _callDuration = 0;

  // 翻译对话
  List<TranslationMessage> _translationMessages = [];

  // ASR临时存储
  Map<String, String> _asrResults = {};

  // 音频控制
  bool _isSpeakerEnabled = true;

  // 字体大小控制
  double _fontSize = 14.0;


  // 音频可视化
  double _micVolume = 0.0;
  Timer? _volumeTimer;

  // 消息列表滚动控制
  final ScrollController _messageScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _initializeRoom();

    // 设置语言参数
    if (widget.fromLanguage != null) {
      _fromLanguage = widget.fromLanguage!;
      log.d('📝 收到源语言参数: ${widget.fromLanguage}');
    }
    if (widget.toLanguage != null) {
      _toLanguage = widget.toLanguage!;
      log.d('📝 收到目标语言参数: ${widget.toLanguage}');
    }

    log.d('🌐 当前语言设置: $_fromLanguage -> $_toLanguage');

    // 初始化翻译服务
    _initializeTranslationService();

    // 如果需要显示分享面板，延迟显示
    if (widget.showShareSheet) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Future.delayed(const Duration(milliseconds: 1000), () {
          if (mounted) {
            _showShareBottomSheet();
          }
        });
      });
    }

    // 立即开始初始化，但要确保在正确的时机
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _initializeVideoAndJoinRoom();
      }
    });
  }

  /// 初始化翻译服务
  Future<void> _initializeTranslationService() async {
    try {
      log.d('🌐 初始化翻译服务...');

      // 设置回调函数
      _translationService.onConnected = () {
        if (mounted) {
          setState(() {
            _translationServiceConnected = true;
          });
          log.d('✅ 翻译服务连接成功');
        }
      };

      _translationService.onDisconnected = () {
        if (mounted) {
          setState(() {
            _translationServiceConnected = false;
          });
          log.d('🔌 翻译服务连接断开');
        }
      };

      _translationService.onAsrUpdate = (text, asrSid,isLast) {
        log.d('🎤 ASR实时识别: $text');
        // 保存ASR结果
        _asrResults[asrSid] = text;
      };

      // 通过 sourceLanguage 和 targetLanguage 来区分说话者
      _translationService.onTranslation = (text, asrSid, sourceLanguage, targetLanguage) {
        if (mounted) {
          // 获取对应的ASR原文
          final originalText = _asrResults[asrSid] ?? '语音输入';

          // 根据源语言判断说话者
          String sender;
          if (sourceLanguage == _fromLanguage) {
            // 源语言是本地用户设置的语言 -> 本地用户说话
            sender = _userId;
          } else {
            // 源语言不是本地用户设置的语言 -> 远端用户说话
            sender = _remoteUsers.isNotEmpty ? _remoteUsers.first : '远端用户';
          }

          _addTranslationMessage(sender, originalText, text, asrSid);
          // 清理已使用的ASR结果
          _asrResults.remove(asrSid);
        }
      };

      _translationService.onTtsAudio = (audioUrl, asrSid) {
        log.d('🔊 收到TTS音频: $audioUrl (双人通话模式不播放TTS)');
        // 双人通话模式不播放TTS音频，避免影响通话体验
      };

      _translationService.onError = (error) {
        log.d('❌ 翻译服务错误: $error');
        _showError('翻译服务错误: $error');
      };

      _translationService.onSessionEnded = (message) {
        log.d('✅ 翻译会话已结束: $message');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: [
                  const Icon(Icons.check_circle, color: Colors.white, size: 20),
                  const SizedBox(width: 8),
                  Text('翻译会话已结束: $message'),
                ],
              ),
              backgroundColor: Colors.green,
              duration: const Duration(seconds: 2),
              behavior: SnackBarBehavior.floating,
            ),
          );
        }
      };

      // 设置语言映射
      _updateTranslationLanguages();

      log.d('✅ 翻译服务初始化完成');
    } catch (e) {
      log.d('❌ 翻译服务初始化失败: $e');
      _showError('翻译服务初始化失败: $e');
    }
  }

  void _initializeRoom() {
    _roomId = widget.roomId ?? _generateRoomId();
    _userId = widget.userId ?? _generateUserId();
    // 初始化视图ID
    _localViewID = -1;
    _remoteViewID = -1;
  }

  String _generateRoomId() {
    final roomId = 'room_${DateTime.now().millisecondsSinceEpoch}';
    log.d('📝 生成房间ID: $roomId');
    return roomId;
  }

  String _generateUserId() {
    final userId = 'user_${math.Random().nextInt(100000)}';
    log.d('📝 生成用户ID: $userId');
    return userId;
  }

  void _startCallTimer() {
    _callTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          _callDuration++;
        });
      }
    });
  }

  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  Future<void> _initializeVideoAndJoinRoom() async {
    // 防止重复初始化
    if (_isEngineInitialized) return;

    await ZegoExpressEngine.instance.enableCustomAudioRemoteProcessing(true, ZegoCustomAudioProcessConfig(
        ZegoAudioSampleRate.SampleRate16K,
        ZegoAudioChannel.Mono,
        0
      ));

    try {
      log.d('🚀 开始初始化视频通话...');

      // 等待一下确保Widget完全准备好
      await Future.delayed(const Duration(milliseconds: 500));

      // 重新设置事件监听器 - 使用可靠的方式
      await _setupReliableEventListeners();

      // 创建本地视频视图
      await _createLocalVideoView();

      // 创建远端视频视图
      await _createRemoteVideoView();

      // 初始化音频流服务
      await _initializeAudioService();

      // 自动加入房间
      await _joinRoom();

      _isEngineInitialized = true;
      log.d('✅ 视频通话初始化完成');
    } catch (e) {
      log.d('❌ 视频通话初始化失败: $e');
      _showError('视频通话初始化失败: $e');
    }
  }

  /// 初始化音频流服务
  Future<void> _initializeAudioService() async {
    try {
      log.d('🎵 初始化音频流服务...');

      // 初始化音频服务
      await _audioService.initialize(
        onAudioFrame: (side, pcmData) {
          if (!mounted) return;

          // 更新音频帧计数和音量可视化
          setState(() {
            if (side == AudioSide.local) {
              _localAudioFrameCount++;
              // 简单的音量计算
              _updateMicVolume(pcmData);
            } else {
              _remoteAudioFrameCount++;
            }
          });
        },
      );

      // 设置外部发送器 (WebSocket翻译)
      _audioService.setExternalSender((side, pcm) {
        log.d('🔊 发送音频数据到翻译服务: ${side}, ${pcm.length} bytes');
        if (_translationService.isConnected) {
          _translationService.sendAudioData(pcm);
        }
      });

      // 启动音频数据观察器
      await _audioService.startAudioDataObserver();

      setState(() {
        _audioServiceActive = _audioService.isActive;
      });

      log.d('✅ 音频流服务初始化完成');
    } catch (e) {
      log.d('❌ 音频流服务初始化失败: $e');
      _showError('音频流服务初始化失败: $e');
    }
  }

  void _updateMicVolume(Uint8List pcmData) {
    if (pcmData.isEmpty) return;

    // 简单的音量计算
    double sum = 0.0;
    for (int i = 0; i < pcmData.length && i < 1000; i += 2) {
      if (i + 1 < pcmData.length) {
        int sample = (pcmData[i + 1] << 8) | pcmData[i];
        sum += sample * sample;
      }
    }

    double rms = math.sqrt(sum / (pcmData.length / 2));
    _micVolume = (rms / 32768.0).clamp(0.0, 1.0);
  }

  Future<void> _setupReliableEventListeners() async {
    log.d('🎯 设置可靠的事件监听器...');

    // 清理之前的监听器
    _clearEventCallbacks();

    // 等待一下确保清理完成
    await Future.delayed(const Duration(milliseconds: 100));

    // 房间状态变化监听
    ZegoExpressEngine.onRoomStateChanged = (roomID, reason, errorCode, extendedData) {
      log.d('🚩 房间状态变化: roomID=$roomID, reason=$reason, errorCode=$errorCode');
      if (!mounted) return;

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _isJoined = reason == ZegoRoomStateChangedReason.Logined;
          });

          // 如果成功加入房间，开始计时
          if (reason == ZegoRoomStateChangedReason.Logined && errorCode == 0) {
            log.d('🔍 房间连接成功，开始计时...');
            _startCallTimer();
            _queryExistingStreams();
            _startTranslationService();
          }
        }
      });
    };

    // 远端用户进入房间
    ZegoExpressEngine.onRoomUserUpdate = (roomID, updateType, userList) {
      log.d('🚩 房间用户更新: roomID=$roomID, updateType=$updateType');
      userList.forEach((user) {
        log.d('   用户: ${user.userID} ${user.userName}');
      });

      if (!mounted) return;

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            if (updateType == ZegoUpdateType.Add) {
              for (var user in userList) {
                if (!_remoteUsers.contains(user.userID)) {
                  _remoteUsers.add(user.userID);
                  log.d('✅ 远端用户加入: ${user.userID}');
                }
              }
            } else {
              for (var user in userList) {
                _remoteUsers.remove(user.userID);
                log.d('🚪 远端用户离开: ${user.userID}');
              }
            }
          });
        }
      });
    };

    // 远端视频流状态变化 - 这是最关键的
    ZegoExpressEngine.onRoomStreamUpdate = (roomID, updateType, streamList, extendedData) {
      log.d('🚩 房间流更新: roomID=$roomID, updateType=$updateType, 流数量: ${streamList.length}');
      streamList.forEach((stream) {
        log.d('   流: ${stream.streamID} 用户: ${stream.user.userID}');
      });

      if (!mounted) return;

      if (updateType == ZegoUpdateType.Add) {
        for (var stream in streamList) {
          // 确保不是自己的流
          if (!stream.streamID.contains(_userId)) {
            log.d('🎬 发现远端流，准备播放: ${stream.streamID}');
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                _playRemoteStreamWithCheck(stream.streamID);
              }
            });
          } else {
            log.d('⚠️ 跳过自己的流: ${stream.streamID}');
          }
        }
      } else {
        for (var stream in streamList) {
          if (!stream.streamID.contains(_userId)) {
            log.d('🛑 远端流移除: ${stream.streamID}');
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                _stopPlayingRemoteStream(stream.streamID);
              }
            });
          }
        }
      }
    };

    // 发布流状态变化
    ZegoExpressEngine.onPublisherStateUpdate = (streamID, state, errorCode, extendedData) {
      log.d('🚩 推流状态更新: streamID=$streamID, state=$state, errorCode=$errorCode');
      if (!mounted) return;

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _isPublishing = state == ZegoPublisherState.Publishing;
          });
        }
      });
    };

    // 播放器状态变化 - 监控远端流播放状态
    ZegoExpressEngine.onPlayerStateUpdate = (streamID, state, errorCode, extendedData) {
      log.d('🚩 播放器状态更新: streamID=$streamID, state=$state, errorCode=$errorCode');
      if (!mounted) return;

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _isPlayingRemoteStream = state == ZegoPlayerState.Playing;
          });
        }
      });

      if (errorCode != 0) {
        log.d('❌ 播放器错误: $errorCode');
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _showError('播放远端流出错: $errorCode');
          }
        });
      } else if (state == ZegoPlayerState.Playing) {
        log.d('✅ 远端流播放成功: $streamID');
      }
    };

    // 远端视频尺寸变化 - 确认远端视频是否有内容
    ZegoExpressEngine.onPlayerVideoSizeChanged = (streamID, width, height) {
      log.d('📐 远端视频尺寸变化: streamID=$streamID, size=${width}x${height}');
      if (!mounted) return;

      if (width > 0 && height > 0) {
        log.d('✅ 远端视频有内容，尺寸: ${width}x${height}');
      }
    };

    log.d('✅ 事件监听器设置完成');
  }

  Future<void> _createLocalVideoView() async {
    try {
      if (_localViewID == -1) {
        log.d('📺 创建本地视频视图...');
        _localVideoView = await ZegoExpressEngine.instance.createCanvasView((viewID) {
          _localViewID = viewID;
          // 启动预览
          ZegoCanvas canvas = ZegoCanvas.view(viewID);
          ZegoExpressEngine.instance.startPreview(canvas: canvas);
          log.d('✅ 开始本地预览, viewID: $viewID');
        }, key: ValueKey('local_${DateTime.now().millisecondsSinceEpoch}'));

        if (mounted) {
          setState(() {});
        }
      } else {
        // 如果视图已存在，直接启动预览
        ZegoCanvas canvas = ZegoCanvas.view(_localViewID);
        ZegoExpressEngine.instance.startPreview(canvas: canvas);
        log.d('✅ 重新开始本地预览, viewID: $_localViewID');
      }
    } catch (e) {
      log.d('❌ 创建本地视频视图失败: $e');
      _showError('创建本地视频视图失败: $e');
    }
  }

  Future<void> _createRemoteVideoView() async {
    try {
      if (_remoteViewID == -1) {
        log.d('📺 创建远端视频视图...');
        _remoteVideoView = await ZegoExpressEngine.instance.createCanvasView((viewID) {
          _remoteViewID = viewID;
          log.d('✅ 创建远端视频视图, viewID: $viewID');
        }, key: ValueKey('remote_${DateTime.now().millisecondsSinceEpoch}'));

        if (mounted) {
          setState(() {});
        }
      }
    } catch (e) {
      log.d('❌ 创建远端视频视图失败: $e');
    }
  }

  Future<void> _joinRoom() async {
    if (_isJoined) return;

    try {
      // 检查引擎状态 - 双重保险
      try {
        final version = await ZegoExpressEngine.getVersion();
        if (version.isEmpty) {
          throw Exception('引擎未就绪');
        }
        log.d('🔍 引擎状态检查通过，版本: $version');
      } catch (e) {
        log.d('⚠️ 引擎状态检查失败: $e');
        throw Exception('引擎未就绪，请稍后重试');
      }

      // 创建用户对象
      ZegoUser user = ZegoUser(_userId, _userId);

      // 房间配置
      ZegoRoomConfig config = ZegoRoomConfig.defaultConfig();
      config.isUserStatusNotify = true;
      config.maxMemberCount = 2;// 最大房间人数

      // 加入房间
      log.d('🚪 开始加入房间: $_roomId, 用户: $_userId');
      await ZegoExpressEngine.instance.loginRoom(_roomId, user, config: config);

      // 开始推流
      await _startPublishing();

    } catch (e) {
      log.d('❌ 加入房间失败: $e');
      _showError('加入房间失败: $e');
    }
  }

  Future<void> _startPublishing() async {
    if (_isPublishing) return;

    try {
      // 检查是否已经加入房间
      if (!_isJoined) {
        log.d('⚠️ 还未加入房间，等待中...');
        await Future.delayed(const Duration(milliseconds: 1000));
        if (!_isJoined) {
          throw Exception('房间未连接');
        }
      }

      final streamID = '${_roomId}_${_userId}_main';
      log.d('📤 开始推流: $streamID');
      await ZegoExpressEngine.instance.startPublishingStream(streamID);

      log.d('✅ 推流已启动');
    } catch (e) {
      log.d('❌ 开始推流失败: $e');

      // 重试机制，特别是针对 1003023 错误
      if (e.toString().contains('1003023')) {
        log.d('🔄 检测到推流失败错误(1003023)，3秒后重试...');
        await Future.delayed(const Duration(seconds: 3));

        try {
          final retryStreamID = '${_roomId}_${_userId}_main';
          await ZegoExpressEngine.instance.startPublishingStream(retryStreamID);
          log.d('✅ 重试推流成功');
        } catch (retryError) {
          log.d('❌ 重试推流失败: $retryError');
          _showError('推流失败，请检查网络连接');
        }
      } else {
        _showError('开始推流失败: $e');
      }
    }
  }

  Future<void> _playRemoteStreamWithCheck(String streamID) async {
    log.d('🔍 检查远端视频视图状态: viewID=$_remoteViewID');

    // 如果远端视图还没创建，先创建
    if (_remoteViewID == -1 || _remoteVideoView == null) {
      log.d('📺 远端视频视图不存在，创建中...');
      await _createRemoteVideoView();

      // 等待足够的时间确保视图创建完成
      await Future.delayed(const Duration(milliseconds: 300));
    }

    if (_remoteViewID == -1) {
      log.d('❌ 远端视频视图创建失败，无法播放流');
      return;
    }

    try {
      ZegoCanvas canvas = ZegoCanvas.view(_remoteViewID);
      await ZegoExpressEngine.instance.startPlayingStream(streamID, canvas: canvas);
      log.d('📥 开始播放远端流: $streamID, viewID: $_remoteViewID');
    } catch (e) {
      log.d('❌ 播放远端流失败: $e');
      _showError('播放远端流失败: $e');
    }
  }

  Future<void> _stopPlayingRemoteStream(String streamID) async {
    try {
      await ZegoExpressEngine.instance.stopPlayingStream(streamID);
      log.d('🛑 停止播放远端流: $streamID');

      if (!mounted) return;

      setState(() {
        _isPlayingRemoteStream = false;
      });
    } catch (e) {
      log.d('❌ 停止播放远端流失败: $e');
    }
  }

  Future<void> _leaveRoom() async {
    if (!_isJoined) return;

    try {
      // 停止计时器
      _callTimer?.cancel();
      _volumeTimer?.cancel();

      // 停止翻译服务
      await _stopTranslationService();

      // 停止推流
      if (_isPublishing) {
        await ZegoExpressEngine.instance.stopPublishingStream();
        log.d('🛑 停止推流');
      }

      // 停止预览
      await ZegoExpressEngine.instance.stopPreview();
      log.d('🛑 停止预览');

      // 离开房间
      await ZegoExpressEngine.instance.logoutRoom(_roomId);
      log.d('🚪 离开房间: $_roomId');

      if (!mounted) return;

      setState(() {
        _isJoined = false;
        _isPublishing = false;
        _isPlayingRemoteStream = false;
        _remoteUsers.clear();
      });
    } catch (e) {
      log.d('❌ 离开房间失败: $e');
      _showError('离开房间失败: $e');
    }
  }

  void _toggleMicrophone() {
    setState(() {
      _isMicEnabled = !_isMicEnabled;
    });
    ZegoExpressEngine.instance.muteMicrophone(!_isMicEnabled);
  }

  void _toggleCamera() {
    setState(() {
      _isCameraEnabled = !_isCameraEnabled;
    });
    ZegoExpressEngine.instance.enableCamera(_isCameraEnabled);
  }

  void _switchCamera() {
    setState(() {
      _isFrontCamera = !_isFrontCamera;
    });
    ZegoExpressEngine.instance.useFrontCamera(_isFrontCamera);
  }

  /// 切换扬声器
  void _toggleSpeaker() {
    setState(() {
      _isSpeakerEnabled = !_isSpeakerEnabled;
    });
    // 切换音频输出设备
    ZegoExpressEngine.instance.setAudioRouteToSpeaker(_isSpeakerEnabled);
    log.d('🔊 扬声器状态: ${_isSpeakerEnabled ? "开启" : "关闭"}');
  }

  /// 显示字体大小调整对话框
  void _showFontSizeDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('字体大小调整'),
        content: StatefulBuilder(
          builder: (context, setState) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '当前字体大小: ${_fontSize.toStringAsFixed(0)}',
                  style: TextStyle(fontSize: _fontSize),
                ),
                const SizedBox(height: 16),
                Slider(
                  value: _fontSize,
                  min: 10.0,
                  max: 20.0,
                  divisions: 10,
                  label: _fontSize.toStringAsFixed(0),
                  onChanged: (value) {
                    setState(() {
                      _fontSize = value;
                    });
                  },
                ),
                const SizedBox(height: 16),
                Text(
                  '预览效果：这是一段示例文字',
                  style: TextStyle(fontSize: _fontSize),
                ),
              ],
            );
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                // 字体大小已经在对话框中更新了
              });
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 复制翻译内容到剪贴板
  Future<void> _copyTranslationToClipboard(TranslationMessage message) async {
    final content = '原文: ${message.originalText}\n翻译: ${message.translatedText}';
    await Clipboard.setData(ClipboardData(text: content));

    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Row(
          children: [
            Icon(Icons.check_circle, color: Colors.white, size: 20),
            SizedBox(width: 8),
            Text('翻译内容已复制到剪贴板'),
          ],
        ),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  void _switchLanguages() {
    setState(() {
      final temp = _fromLanguage;
      _fromLanguage = _toLanguage;
      _toLanguage = temp;
    });
    _updateTranslationLanguages();
  }

  /// 更新翻译服务的语言设置
  void _updateTranslationLanguages() {
    log.d('🔧 更新翻译服务语言设置: $_fromLanguage -> $_toLanguage');
    _translationService.setLanguages(from: _fromLanguage, to: _toLanguage);
  }

  /// 添加翻译消息
  void _addTranslationMessage(String sender, String originalText, String translatedText, String asrSid) {
    if (!mounted) return;

    setState(() {
      _translationMessages.add(
        TranslationMessage(
          sender: sender,
          roomId: _roomId,
          originalText: originalText,
          translatedText: translatedText,
          timestamp: DateTime.now(),
        ),
      );
    });

    // 自动滚动到最新消息
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_messageScrollController.hasClients) {
        _messageScrollController.animateTo(
          _messageScrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  /// 启动翻译服务
  Future<void> _startTranslationService() async {
    try {
      log.d('🌐 启动翻译服务...');
      await _translationService.connect();

      // 连接成功后开始自动检测翻译会话（双人通话模式，禁用TTS）
      if (_translationService.isConnected) {
        await _translationService.startAutoDetectTranslation(
          candidateLanguage1: _fromLanguage,
          candidateLanguage2: _toLanguage,
          tsEnable: true,    // 启用翻译
          ttsEnable: false,  // 双人通话禁用TTS，避免影响通话
        );
        log.d('✅ 自动检测翻译会话已开始: ${_fromLanguage} <-> ${_toLanguage}');
      }
    } catch (e) {
      log.d('❌ 启动翻译服务失败: $e');
      _showError('翻译服务启动失败: $e');
    }
  }

  /// 停止翻译服务
  Future<void> _stopTranslationService() async {
    try {
      if (_translationService.isConnected) {
        await _translationService.endTranslation();
        await _translationService.disconnect();
        log.d('🌐 翻译服务已停止');
      }
    } catch (e) {
      log.d('❌ 停止翻译服务失败: $e');
    }
  }

  void _showError(String message) {
    log.d('❌ 错误: $message');
    if (mounted) {
      try {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(message),
            backgroundColor: Colors.red,
          ),
        );
      } catch (e) {
        log.d('❌ 显示错误消息失败: $e');
      }
    }
  }

  void _showEndCallDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('温馨提示'),
        content: const Text('确定要结束目前通话？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showShareBottomSheet() {
    final shareUrl = 'https://uptimetime.com/invite/$_roomId/$_fromLanguage/$_toLanguage';

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                '邀请加入通话',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 20),

              // 房间ID
              _buildShareItem('房间ID', _roomId),

              const SizedBox(height: 16),

              // 分享链接
              _buildShareItem('分享链接', shareUrl),

              const SizedBox(height: 24),

              // 取消按钮
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '取消',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildShareItem(String label, String value) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.withValues(alpha: 0.3)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(
              color: Colors.grey,
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 4),
          Row(
            children: [
              Expanded(
                child: Text(
                  value,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              GestureDetector(
                onTap: () => _copyToClipboardInVideo(value),
                child: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.blue.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: const Icon(
                    Icons.copy,
                    size: 16,
                    color: Colors.blue,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Future<void> _copyToClipboardInVideo(String text) async {
    await Clipboard.setData(ClipboardData(text: text));
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.check_circle, color: Colors.white, size: 20),
            const SizedBox(width: 8),
            Text(
              text.startsWith('http') ? '链接已复制到剪贴板' : '房间号已复制到剪贴板',
            ),
          ],
        ),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  void _clearLocalVideoView() {
    // 清理本地视频视图以释放资源和避免内存泄漏
    if (_localViewID != -1) {
      ZegoExpressEngine.instance.destroyCanvasView(_localViewID);
      _localViewID = -1;
      _localVideoView = null;
      log.d('🧹 清理本地视频视图');
    }
  }

  void _clearRemoteVideoView() {
    // 清理远端视频视图以释放资源和避免内存泄漏
    if (_remoteViewID != -1) {
      ZegoExpressEngine.instance.destroyCanvasView(_remoteViewID);
      _remoteViewID = -1;
      _remoteVideoView = null;
      log.d('🧹 清理远端视频视图');
    }
  }

  Future<void> _queryExistingStreams() async {
    try {
      // 延迟一下，确保房间状态稳定
      await Future.delayed(const Duration(milliseconds: 500));

      log.d('🔍 查询房间中的现有流...');

      // 注意：ZegoExpressEngine 没有直接的 getStreamList 方法
      // 但是当我们加入房间时，如果房间中已有流，会触发 onRoomStreamUpdate 事件
      // 这里我们主要是确保远端视频视图已经准备好
      if (_remoteViewID == -1 || _remoteVideoView == null) {
        log.d('📺 确保远端视频视图已创建...');
        await _createRemoteVideoView();
      }

      log.d('✅ 查询现有流完成');
    } catch (e) {
      log.d('❌ 查询现有流失败: $e');
    }
  }

  void _clearEventCallbacks() {
    ZegoExpressEngine.onRoomStateChanged = null;
    ZegoExpressEngine.onRoomUserUpdate = null;
    ZegoExpressEngine.onRoomStreamUpdate = null;
    ZegoExpressEngine.onPublisherStateUpdate = null;
    ZegoExpressEngine.onPlayerStateUpdate = null;
    ZegoExpressEngine.onPlayerVideoSizeChanged = null;
    log.d('🧹 清理事件回调');
  }


  @override
  void dispose() {
    _callTimer?.cancel();
    _volumeTimer?.cancel();
    _messageScrollController.dispose();
    _leaveRoom();
    _clearLocalVideoView();
    _clearRemoteVideoView();
    _clearEventCallbacks();

    // 停止音频流服务
    _audioService.dispose();

    // 停止翻译服务
    _translationService.dispose();

    // 销毁引擎，避免重复创建导致的冲突
    try {
      ZegoExpressEngine.destroyEngine();
      log.d('✅ 引擎已销毁');

      // 重置引擎状态
      VideoChatScreen.resetEngineState();

    } catch (e) {
      log.d('⚠️ 引擎销毁失败: $e');
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          // 顶部状态栏和语言选择
          Container(
            padding: const EdgeInsets.fromLTRB(16, 50, 16, 16),
            child: Row(
              children: [
                // 返回按钮
                IconButton(
                  icon: const Icon(Icons.arrow_back, color: Colors.white),
                  onPressed: () => Navigator.pop(context),
                ),
                // 语言选择区域
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      color: Colors.black.withValues(alpha: 0.8),
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: Colors.white.withValues(alpha: 0.3)),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // 简化的语言显示
                        Flexible(
                          child: Text(
                            LanguageCodes.getLanguageName(_fromLanguage),
                            style: const TextStyle(color: Colors.white, fontSize: 12),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 6),
                        GestureDetector(
                          onTap: _switchLanguages,
                          child: const Icon(
                            Icons.swap_horiz,
                            color: Colors.white,
                            size: 16,
                          ),
                        ),
                        const SizedBox(width: 6),
                        Flexible(
                          child: Text(
                            LanguageCodes.getLanguageName(_toLanguage),
                            style: const TextStyle(color: Colors.white, fontSize: 12),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Text(
                          'ID: ${_roomId.replaceAll('room_', '').substring(0, 6)}',
                          style: const TextStyle(color: Colors.white70, fontSize: 10),
                        ),
                        const SizedBox(width: 6),
                        // 翻译服务连接状态指示器
                        Container(
                          width: 6,
                          height: 6,
                          decoration: BoxDecoration(
                            color: _translationServiceConnected ? Colors.green : Colors.red,
                            shape: BoxShape.circle,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 视频区域 - 左右分屏
          Expanded(
            flex: 2,
            child: Row(
              children: [
                // 左侧 - 本地视频
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.all(4),
                    decoration: BoxDecoration(
                      color: Colors.grey[800],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: _localVideoView != null
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: _localVideoView!,
                          )
                        : const Center(
                            child: Icon(
                              Icons.person,
                              color: Colors.white,
                              size: 48,
                            ),
                          ),
                  ),
                ),

                // 右侧 - 远端视频或等待状态
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.all(4),
                    decoration: BoxDecoration(
                      color: Colors.grey[900],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: _isPlayingRemoteStream && _remoteVideoView != null
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: _remoteVideoView!,
                          )
                        : Stack(
                            children: [
                              // 等待背景
                              Container(
                                width: double.infinity,
                                height: double.infinity,
                                decoration: BoxDecoration(
                                  color: Colors.black,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                              // 等待提示
                              const Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.person_add,
                                      color: Colors.white,
                                      size: 48,
                                    ),
                                    SizedBox(height: 16),
                                    Text(
                                      '正在等待好友加入通话...',
                                      style: TextStyle(color: Colors.white, fontSize: 14),
                                    ),
                                  ],
                                ),
                              ),
                              // 等待气泡
                              if (_remoteUsers.isEmpty)
                                Positioned(
                                  top: 16,
                                  left: 16,
                                  right: 16,
                                  child: Container(
                                    padding: const EdgeInsets.all(12),
                                    decoration: BoxDecoration(
                                      color: Colors.grey[700],
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: const Text(
                                      '正在等待好友加入通话...',
                                      style: TextStyle(color: Colors.white, fontSize: 12),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                  ),
                ),
              ],
            ),
          ),

          // 翻译对话区域
          Expanded(
            flex: 3,
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '系统提示',
                    style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    '请勿发布包含色情、违法、侵权等不当内容，对于发布违规的用户，本平台拥有依据国家法规及平台规则进行处理的权利。',
                    style: TextStyle(color: Colors.grey, fontSize: 12),
                  ),
                  const SizedBox(height: 16),

                  // 翻译消息列表
                  Expanded(
                    child: ListView.builder(
                      controller: _messageScrollController,
                      itemCount: _translationMessages.length,
                      itemBuilder: (context, index) {
                        final message = _translationMessages[index];
                        return _buildTranslationMessage(message);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 底部控制栏
          Container(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 麦克风控制（带音量可视化）
                _buildMicrophoneButton(),

                // 声音控制
                _buildControlButton(
                  icon: _isSpeakerEnabled ? Icons.volume_up : Icons.volume_off,
                  label: '扬声器',
                  isActive: _isSpeakerEnabled,
                  onTap: _toggleSpeaker,
                ),

                // 挂断按钮 - 显示时间
                _buildHangupButton(),

                // 摄像头控制
                _buildControlButton(
                  icon: _isCameraEnabled ? Icons.videocam : Icons.videocam_off,
                  label: '摄像头',
                  isActive: _isCameraEnabled,
                  onTap: _toggleCamera,
                ),

                // 字体大小调整
                _buildControlButton(
                  icon: Icons.text_fields,
                  label: '字体大小',
                  isActive: false,
                  onTap: _showFontSizeDialog,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildControlButton({
    required IconData icon,
    required String label,
    required bool isActive,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: isActive ? Colors.white.withValues(alpha: 0.2) : Colors.black.withValues(alpha: 0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 24,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHangupButton() {
    return GestureDetector(
      onTap: _showEndCallDialog,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: const BoxDecoration(
              color: Colors.red,
              shape: BoxShape.circle,
            ),
            child: const Icon(
              Icons.call_end,
              color: Colors.white,
              size: 24,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            _formatDuration(_callDuration),
            style: const TextStyle(
              color: Colors.white,
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTranslationMessage(TranslationMessage message) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户头像
          CircleAvatar(
            radius: 12,
            backgroundColor: Colors.grey[600],
            child: Text(
              message.sender.substring(0, 1).toUpperCase(),
              style: const TextStyle(color: Colors.white, fontSize: 10),
            ),
          ),
          const SizedBox(width: 8),

          // 翻译气泡 - 原文和翻译在同一个气泡中
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 发送者和房间ID
                Text(
                  '${message.sender} ${message.roomId}',
                  style: const TextStyle(color: Colors.grey, fontSize: 10),
                ),
                const SizedBox(height: 4),

                // 原文和翻译合并的气泡
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 原文
                      Text(
                        message.originalText,
                        style: TextStyle(color: Colors.white, fontSize: _fontSize),
                      ),
                      const SizedBox(height: 4),
                      // 翻译文本
                      Text(
                        message.translatedText,
                        style: TextStyle(color: Colors.white, fontSize: _fontSize),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 复制按钮
          IconButton(
            icon: const Icon(Icons.copy, color: Colors.white, size: 16),
            onPressed: () => _copyTranslationToClipboard(message),
          ),
        ],
      ),
    );
  }

  Widget _buildMicrophoneButton() {
    return GestureDetector(
      onTap: _toggleMicrophone,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              // 音量可视化圆环
              if (_isMicEnabled)
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: Colors.green.withValues(alpha: _micVolume),
                      width: 3,
                    ),
                  ),
                ),
              // 麦克风按钮
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: _isMicEnabled ? Colors.green.withValues(alpha: 0.8) : Colors.red.withValues(alpha: 0.8),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  _isMicEnabled ? Icons.mic : Icons.mic_off,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          const Text(
            '麦克风',
            style: TextStyle(
              color: Colors.white,
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }
}

// 翻译消息模型
class TranslationMessage {
  final String sender;
  final String roomId;
  final String originalText;
  final String translatedText;
  final DateTime timestamp;

  TranslationMessage({
    required this.sender,
    required this.roomId,
    required this.originalText,
    required this.translatedText,
    required this.timestamp,
  });
}
